import $ from './util/jquery.js';
import dot from 'dot';
import Component from './cmp/Component.js';
import {config, replacePrefix, isNoCache, globalConfig} from './config/config.js';
import util from './util/util.js';

const version= '1.0.0';

(function($,window){
	window.doT = dot ;
	let hasAmd = typeof define === 'function' && define.amd;
	let cmpCache = util.emptyObject();
	let routeInited = false ;
	let hashRouteNoHandlerFlag = false ;
	
	/**
	 * 初始化一个组件对象，并返回jQuery延迟对象
	 * @param {String} url 处理过的html请求地址
	 */
	function initComponent(url){
		let def = $.Deferred();
		let cmp ;
		// TODO config中增加配置，可以设置ajax属性，这里使用ajax方法
		// TODO 404等问题处理
		$.get(url, {}, $.noop, 'html').done(function(html){
			cmp = new Component(html);
			cmpCache[url] = cmp ;
			def.resolve(cmp);
		}).fail(function(jqXhr,status,msg){
			def.reject(jqXhr,status,msg);
		});
		return def ;
	}
	
	/**
	 * 解析url，并取得一个对象，可以获取到url参数和url值
	 * url参数一定不是空，如果没有则返回{}
	 */
	function parseUrl(url){
		let i = url.indexOf('?');
		let obj = {
			queryParam : util.emptyObject(),
			url: i === -1 ? url : url.substring(0,i)
		};
		if (i !== -1) {
			let query = url.substr(i + 1);
			let kvs = query.split('&');
			for (let x = 0 ; x < kvs.length ; x ++) {
				let point = kvs[x].indexOf('=');
				if (point !== -1) {
					let k = kvs[x].substring(0,point);
					let v = kvs[x].substring(point + 1);
					if (k) {
						obj.queryParam[k] = v;
					}
				}
			}
		}
		
		return obj ;
	}
	
	// 初始化SPA全局对象
	$.spa = {
		version,
		config,
		render($dom,url,params) {
			url = replacePrefix(url);
			if (!url) {
				return $.Deferred().reject('未指定url！');
			}
			
			let urlInfo = parseUrl(url);
			
			if (!isNoCache() && cmpCache[urlInfo.url]) {
				return cmpCache[urlInfo.url].render($dom,params,urlInfo.queryParam);
			} else {
				let def = $.Deferred();
				initComponent(urlInfo.url).done(function(cmp){
					cmp.render($dom,params,urlInfo.queryParam).then(() => {
						def.resolve();
					},() => {
						def.reject();
					});
				});
				return def ;
			}
		},
		// hash 路由处理
		route: {
			changeHashOnly(hash) {
				hashRouteNoHandlerFlag = true ;
				location.hash = hash ;
			},
			
			// 初始化hash路由功能
			init(){
				if (routeInited) {
					return ;
				}
				routeInited = true ;
				function doHashChange(){
					if (hashRouteNoHandlerFlag) {
						hashRouteNoHandlerFlag = false ;
						return ;
					}
					let hashUrl ;
					if (location.hash) {
						hashUrl = location.hash.substr(1);
					} else {
						return ;
					}
					let $dom = globalConfig.getHashChangeRenderDom(hashUrl);
					if ($dom && $dom.jquery && $dom.render) {
						$dom.render(hashUrl);
					}
				}
				window.addEventListener('hashchange',doHashChange);
				
				// 第一次读取hash
				if (location.hash) {
					doHashChange();
				}
				
			}
		}
	}
	
	$.fn.render = function(url,params){
		$.spa.render(this,url,params);
	}
	
})($,window);

export default $.spa ;